# -*- coding: utf-8 -*-
# Author: xiantingDeng
# File: conftest.py
# Time: 17:23

import os
import pytest
import allure
from selenium import webdriver
from common.utils.log_util import logger
from common.utils.config import driver_config as config
from common.utils.file_util import get_img_file_path


# 屏幕截图专用driver
screenshot_driver = None

@pytest.fixture(scope="session")
def log():
    #生成全局log日志工具
    global log
    log = logger()
    return log

@pytest.hookimpl(tryfirst=True,hookwrapper=True)
def pytest_runtest_makereport(item,call):
    outcome = yield
    rep = outcome.get_result()
    # we only look at actual failing test calls, not setup/teardown
    if rep.when == "call" and rep.failed:
        # mode = "a" if os.path.exists("failures") else "w"
        # with open("failures", mode) as f:
        #     # let's also access a fixture for the fun of it
        #     if "tmpdir" in item.fixturenames:
        #         extra = " (%s)" % item.funcargs["tmpdir"]
        #     else:
        #         extra = ""
        #     f.write(rep.nodeid + extra + "\n")
        img_name = get_img_file_path("用例失败截图")
        screenshot_driver.save_screenshot(img_name)
        with open(img_name, mode="rb") as f:
            file = f.read()
        allure.attach(file, "失败截图", allure.attachment_type.PNG)
        # 调用截图函数

@pytest.fixture(scope="session")
def driver(log):
    log.debug("读取配置信息：{}".format(config))
    try:
        log.debug("正在启动driver")
        driver = webdriver.Chrome()
        driver.implicitly_wait(10)
        global screenshot_driver
        screenshot_driver = driver
        log.debug("当前运行的环境是：{}".format(config.get("environment")))
        driver.implicitly_wait(10)
        log.debug("打开：{}".format(config.get("url")))
        driver.get(config.get("url"))
        return driver
    except Exception as e:
        log.error("driver启动失败，失败原因：{}".format(e))
        raise

